package com.diao.myhub.controller;

import com.diao.myhub.cache.HotTagCache;
import com.diao.myhub.model.dto.PaginationDTO;
import com.diao.myhub.service.NotifyService;
import com.diao.myhub.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private HotTagCache hotTagCache;
    private QuestionService questionService;
    @Autowired
    public void setQuestionService(QuestionService questionService) {
        this.questionService = questionService;
    }
//    @GetMapping({"/","/index/{page}","/main","/index"})
    public String index(Model model,
                        @RequestParam("search") @Nullable String search,
                        @RequestParam("userId") @Nullable Integer userId,
                        @Nullable String tag,
                        @PathVariable("page") @Nullable Integer page){
        if (page==null || page<0){
            page = 1;
        }
        List<String> keyList = null;
        if (StringUtils.hasText(search)) {
            keyList = Arrays.stream(search.split(" ")).toList();
        }
        PaginationDTO paginationDTO = questionService.getQuestions(tag, keyList, page, userId);
        model.addAttribute("quez",paginationDTO);
        model.addAttribute("hotTags",hotTagCache.getHotTags());
        model.addAttribute("userId", userId);
        return "index";
    }
}
